<?php
namespace hema\wechat;

use app\common\model\Setting;
use hema\Http;

class Map
{
    private $map_key;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $values = Setting::getItem('web',0);//获取站点配置
        $this->map_key = $values['wxmap'];
    }


    /**
     * 计算距离
     * $from 起点，$to 终点
     * $mode 计算方式：driving（驾车）、walking（步行）bicycling：自行车
     */
    public function getDistance(string $from, string $to, string $mode='driving')
    {
        $key = $this->map_key;
        $url = 'https://apis.map.qq.com/ws/distance/v1/matrix?parameters';
        $queryarr = [
            'mode' => $mode,
            'from' => $from,
            'to' => $to,
            'key' => $key            
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
        if ($result['status']!=0) {
            return false;
        }
        return $result['result']['rows'][0]['elements'];
        /*
        返回数组：[{distance=米,  duration=秒}]
        distance：起点到终点的距离，单位：米
        duration：表示从起点到终点的结合路况的时间，秒为单位
         */
    }
    
    /**
     * 逆地址解析(坐标位置描述)
     */
    public function getLocation(string $location)
    {
        $key = $this->map_key;
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?location='.$location.'&key='.$key.'&get_poi=1';
        $result = json_decode(Http::get($url),true);
        if ($result['status'] != 0) {
            return false;
        }
        $result['result']['address_component']['poi_id'] = '';
        //获取poi_id
        if(isset($result['result']['pois'][0])){
            $result['result']['address_component']['poi_id'] = $result['result']['pois'][0]['id'];
        }
        return $result['result']['address_component'];
    }   

}
